<?php

namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 短信验证码
 */
class FishingGroundOrders extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $insert = ['status' => 1];
    // 追加属性
    protected $append = [
    ];

    public function getCreateTimeAttr($value)
    {
        return is_numeric($value) ? date('Y-m-d H:i:s', $value) : $value;
    }

    public function getUpdateTimeAttr($value)
    {
        return is_numeric($value) ? date('Y-m-d H:i:s', $value) : $value;
    }

    public function positions()
    {
        return $this->belongsTo(FishingGroundPositions::class, 'id', 'position_id');
    }

    public function groups()
    {
        return $this->hasMany(FishingGroundOrdersGroups::class, 'id', 'order_id');
    }

    /**
     * 拼团成功
     * @param $orderId
     */
    public function groupSucess($orderId)
    {
        $row_info = self::find($orderId);
        $row_info->grouptime = time();
        $row_info->status = 2;
        $row_info->save();

        (new FishingGroundOrdersGroups)->groupSucess($orderId);
    }

    /**
     * 拼团失败
     * @param $orderId
     */
    public function groupFail($orderId)
    {
        Db::startTrans();
        try {

            $row_info = self::find($orderId);
            $row_info->status = 3;
            $row_info->save();

            (new FishingGroundOrdersGroups)->groupFail($orderId);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

    }
}
